'use strict';

var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var imagemin = require('gulp-imagemin');
var prefix = require('gulp-autoprefixer');
var rjs = require('requirejs')

//# 后台目标文件dir
//
var backendDist = (function() {
    return {
        css: './public/backend/dist/css',
        js: './public/backend/dist/js',
        image: './public/backend/dist/image',
        font: './public/backend/dist/fonts'
    };
}());

//# 后台原文件
//
var backednSrc = (function() {
    return {
        sass: {
            main: [
                './public/backend/src/sass/index.scss',
            ],
            files: ['./public/backend/src/sass/**/*.scss']
        },
        css: {
            main: []
        },
        js: {
            main: ['./public/backend/src/js/wedstudio.js'],
            files: ['./public/backend/src/js/**/*.js']
        },
        image: {
            files: ['./public/backend/src/image/**/**']
        },
        font: {
            files: ['./public/backend/src/fonts/**/**']
        }

    };
}());

//# tasks
//## sass编译为css
//
gulp.task('backend-css', function() {
    gulp.src(backednSrc.sass.main)
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(sass())
        .pipe(prefix())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(backendDist.css));
});

//## require打包
//
gulp.task('backend-js', function(cb) {
    rjs.optimize({
        baseUrl: "./public/backend/src/js",
        dir: "./public/backend/dist/js",
        keepBuildDir: false,
        removeCombined: true,
        optimizeCss: "standard",
        mainConfigFile: './public/backend/src/js/wedstudio.js',
        findNestedDependencies: true,
        modules: [{
            name: 'wedstudio'
        }],
    }, function(buildRes) {
        console.log(buildRes);
    }, cb);
});

//## image压缩
//
gulp.task('backend-image', function() {
    return gulp.src(backednSrc.image.files)
        .pipe(imagemin())
        .pipe(gulp.dest(backendDist.image))
});

//## font拷贝
//
gulp.task('backend-font', function() {
    gulp.src(backednSrc.font.files)
        .pipe(gulp.dest(backendDist.font));

});

gulp.task('build', ['backend-css', 'backend-js', 'backend-image', 'backend-font']);

gulp.task('default', function() {
    gulp.start(['build']);
    gulp.watch(backednSrc.sass.files, ['backend-css']);
    gulp.watch(backednSrc.js.files, ['backend-js']);
    gulp.watch(backednSrc.font.files, ['backend-font']);
    gulp.watch(backednSrc.image.files, ['backend-image']);
});